#pragma once
#include <iostream>
#include <cerrno>
#include <cstring>

#include <sys/epoll.h>
#include <unistd.h>

#include "mydll/log.hpp"
#include "mydll/err.hpp"

class Epoller
{
    const static int defauepfd = -1;
    const static int gsize = 128;
public:
    Epoller()
        :_epfd(defauepfd)
    {}

    void Create()
    {
        _epfd = epoll_create(gsize);
        if(_epfd < 0)
        {
            logMessage(Fatal,"epoll file create error! code: %d,string error: %s",errno,strerror(errno));
            exit(EPOLL_CREATE_ERR);
        }
    }

    bool AddModEvent(int _fd,uint32_t _event,int op) //客户端文件描述符 监测事件
    {
        struct epoll_event event;
        event.data.fd = _fd;
        event.events = _event;
        int n = epoll_ctl(_epfd,op,_fd,&event);
        if(n < 0)
        {
            logMessage(Warning,"AddEvent error! errno: %d,string error: %s",errno,strerror(errno));
            return false;
        }
        return true;
    }

    bool DelEvent(int _fd)
    {
        return epoll_ctl(_epfd,EPOLL_CTL_DEL,_fd,nullptr) == 0;
    }

    int Wait(epoll_event* _event,int _maxevents,int _timeout)
    {
        return epoll_wait(_epfd,_event,_maxevents,_timeout);
    }

    int GetEpfd() { return _epfd; }

    void Close() 
    {
        if(_epfd != defauepfd) close(_epfd);
        _epfd = defauepfd;
    }

    ~Epoller() { Close(); }
private:
    int _epfd;
};